<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="isDealName" :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <MainBodySelect
              v-model="form.dealId"
              :scope-authority="true"
              parameters="deal"
              @change="changeDeal"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资日期')" prop="changeDate">
            <el-date-picker
              v-model="form.changeDate"
              align="right"
              type="date"
              :placeholder="$t('融资日期')"
              :picker-options="pickerOptions"
              @change="getWebRate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资轮次')" prop="rounds">
            <el-input v-model="form.rounds" :placeholder="$t('融资轮次')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资总金额') + $t('金额单位')" prop="amountFinancing">
            <Money v-model="form.amountFinancing" unit="w" :placeholder="$t('融资总金额') + $t('金额单位')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <el-select v-model="form.currency" :placeholder="$t('币种')" @change="settingHoldShareCurrency">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('公司类型')" prop="companyType">
            <dictSelect
              v-model="form.companyType"
              :clearable="true"
              dictionary="company_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资方式')" prop="roundsType">
            <dictSelect
              v-model="form.roundsType"
              :clearable="true"
              dictionary="financing_mode"
            />
          </el-form-item>
        </el-col>
        <!--
        <el-col :span="12">
          <el-form-item :label="$t('企业阶段')" prop="enterpriseStage">
            <el-input v-model="form.enterpriseStage" :placeholder="$t('企业阶段')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        -->
        <el-col :span="12">
          <el-form-item :label="$t('融资前公司估值') + $t('金额单位')" prop="beforeValuation">
            <span slot="label">
              {{ $t('融资前公司估值') }} {{ $t('金额单位') }}
            </span>
            <Money v-model="form.beforeValuation" unit="w" :placeholder="$t('融资前公司估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资后公司估值') + $t('金额单位')" prop="afterValuation">
            <span slot="label">
              {{ $t('融资后公司估值') }} {{ $t('金额单位') }}
            </span>
            <Money v-model="form.afterValuation" unit="w" :placeholder="$t('融资后公司估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="beforeShareNum">
            <span slot="label">
              <span v-if="form.companyType === 'GFGS'">{{ $t('融资前-公司总股数(万股)') }}</span>
              <span v-else-if="form.companyType === 'YXGS'">{{ $t('融资前-注册资本(万)') }}</span>
              <span v-else>{{ $t('融资前-公司总股数(万股)/注册资本(万)') }}</span>
            </span>
            <Money v-model="form.beforeShareNum" unit="w" :placeholder="$t('融资后-公司总股数(万股)/注册资本(万)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="afterShareNum">
            <span slot="label">
              <span v-if="form.companyType === 'GFGS'">{{ $t('融资后-公司总股数(万股)') }}</span>
              <span v-else-if="form.companyType === 'YXGS'">{{ $t('融资后-注册资本(万)') }}</span>
              <span v-else>{{ $t('融资后-公司总股数(万股)/注册资本(万)') }}</span>
            </span>
            <Money v-model="form.afterShareNum" unit="w" :placeholder="$t('融资后-公司总股数(万股)/注册资本(万)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资后每股价格')+ $t('(元)')" prop="afterSharePrice">
            <span slot="label">
              {{ $t('融资后每股价格') }}{{ $t('(元)') }}
              <el-tooltip :content="'本轮投资金额绝对值汇总 / 本轮变更股数绝对值汇总'">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-input v-show="afterSharePriceHide" v-model="form.afterSharePrice" :placeholder="$t('融资后每股价格')" @blur="afterSharePriceChange">
              <template slot="append" icon="el-icon-search">
                <el-checkbox v-model="form.automaticPriceCalculation">{{ $t('自动计算') }}</el-checkbox>
                <el-tooltip :content="$t('选中后自动计算股价或手动录入指定股价')">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
            </el-input>
            <el-input v-show="!afterSharePriceHide" v-model="afterSharePriceNum" @focus="afterSharePriceFocus">
              <template slot="append" icon="el-icon-search">
                <el-checkbox v-model="form.automaticPriceCalculation">{{ $t('自动计算') }}</el-checkbox>
                <el-tooltip :content="$t('选中后自动计算股价或手动录入指定股价')">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
            </el-input>

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关键条款')" prop="termsId">
            <div>
              <el-select v-model="form.termsId" filterable :placeholder="$t('关键条款')" clearable>
                <el-option
                  v-for="(item, index) in termsOptions"
                  :key="index"
                  :label="item.contractName ? item.contractName + '/' + item.typeLabel : item.typeLabel"
                  :value="item.id"
                />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col
          v-for="(item, index) in form.exchangeRateWeb"
          :key="new Date().getTime() + '_' + index"
          :span="12"
        >
          <el-form-item :prop="'exchangeRateWeb.' + index + '.rate'" :rules="[{ required: true, message: $t('必填信息'), trigger: 'blur' }]">
            <span slot="label">
              {{ $t(formatCurrency(item.sourceCurrency)) }}{{ $t('对') }}{{ $t(formatCurrency(item.targetCurrency)) }}{{ $t('汇率') }}
              <el-tooltip :content="$t('使用') + item.placeholder" placement="right">
                <el-button
                  v-if="item.placeholder !== undefined && item.placeholder !== null && item.placeholder !== ''"
                  class="el-icon-document-copy"
                  size="small"
                  type="text"
                  style="color: #1890ff !important;cursor: pointer;"
                  @click="inputPlaceholder(index, item.placeholder)"
                />
              </el-tooltip>
            </span>
            <el-input-number
              v-model="item.rate"
              :max="999999999"
              :min="0"
              :precision="4"
              :placeholder="item.placeholder"
              :controls="false"
              @change="changeBlurRate($event, item.currency)"
              @blur="changeBlurRate($event, item.currency)"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 变更详情 -->
      <div class="area-header">
        <span class="area-header-title">{{ $t('股权变更详情') }}</span>
        <el-tooltip :content="$t('填写完毕后点击下方计算按钮,才能自动计算对应的数值')" placement="top">
          <i class="el-icon-question" />
        </el-tooltip>
      </div>
      <el-table
        ref="table"
        v-loading="detailLoading"
        :data="form.detailList"
        height="450"
        border
        class="nowrapTable formTable"
        show-summary
        :summary-method="getSummaries"
        row-class-name="cellClass"
        @cell-mouse-enter.once="rowDrop"
      >
        <el-table-column label="" align="center" width="50">
          <div class="handle">
            <i class="el-icon-rank link-type" />
          </div>
        </el-table-column>
        <el-table-column :label="$t('序号')" align="center" min-width="80">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('序号') }}</span>
            <el-tooltip :content="$t('红色序号表示股东为当前项目的出资人')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <span :style="{ color: (scope.row.shareholderId === undefined || scope.row.shareholderId === null || scope.row.shareholderId === '') ? 'black' : 'red'}">{{ (scope.$index + 1) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('股东名称')" align="center" min-width="150">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('股东名称') }}</span>
            <el-tooltip :content="$t('可选择投资主体，也可以手动添加')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.shareholderName'" :rules="detailListRules.shareholderName">
              <el-autocomplete
                id="shareholderName"
                v-model="scope.row.shareholderName"
                popper-class="my-autocomplete"
                :fetch-suggestions="querySearch"
                :placeholder="$t('请输入')"
                @paste.native="pasteMe($event, scope.$index, 'shareholderName')"
                @select="handleSelect($event, scope.row)"
                @change="choiceHoldShare($event, scope.$index)"
              >
                <i
                  slot="suffix"
                  class="el-icon-edit el-input__icon"
                  @click="handleIconClick"
                />
                <template slot-scope="{ item }">
                  <div>{{ item.investorName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-show="!isAll" :label="$t('变更类型')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('变更类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.changeType'" :rules="detailListRules.changeType">
              <el-select v-model="scope.row.changeType" :clearable="true" :placeholder="$t('请选择')" @change="changeTypeMethod($event, scope.$index)">
                <el-option
                  v-for="item in changeTypeOptions"
                  :key="item.dictValue + '_' + scope.$index"
                  :label="$t(item.dictLabel)"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('本轮投资金额') + $t('金额单位')" align="center" min-width="150">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('本轮投资金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.investAmount'" :rules="detailListRules.investAmount">
              <Money v-model="scope.row.investAmount" unit="w" :disabled="scope.row.changeType === 'WBD' ? true : false" @change="jisuan" @paste.native="pasteMe($event, scope.$index, 'investAmount')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!isAll || !editExistShareStatus" :label="$t('已有股数') + $t('(万股)')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('已有股数') + $t('(万股)') }}</span>
            <el-tooltip :content="$t('已有股数 = 上一轮股东的最新持有股数，新股东为0')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.existShare'">
              <Money v-model="scope.row.existShare" unit="w" :disabled="editExistShareStatus && !scope.row.isNew === true" @paste.native="pasteMe($event, scope.$index, 'existShare')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('变更股数') + $t('(万股)')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('变更股数') + $t('(万股)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.resultShare'">
              <Money v-model="scope.row.resultShare" unit="w" :disabled="scope.row.changeType === 'WBD' ? true : false" @change="jisuan" @paste.native="pasteMe($event, scope.$index, 'resultShare')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('最新持有股数') + $t('(万股)')" align="center" min-width="165">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('最新持有股数') + $t('(万股)') }}</span>
            <el-tooltip :content="$t('最新持有股数 = 已有股数 + 变更股数')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.holdShare'" :rules="detailListRules.holdShare">
              <Money v-model="scope.row.holdShare" unit="w" @change="changeHoldShare" @paste.native="pasteMe($event, scope.$index, 'holdShare')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('融资后持股市值') + $t('金额单位')" align="center" min-width="150">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('融资后持股市值') }}{{ $t('金额单位') }}</span>
            <el-tooltip :content="$t('融资后持股市值 = 融资后每股价格 * 当前股东最新持股数')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.shareMarket'">
              <Money v-model="scope.row.shareMarket" unit="w" @change="jisuan" @paste.native="pasteMe($event, scope.$index, 'shareMarket')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('本轮盈利') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('本轮盈利') }}{{ $t('金额单位') }}</span>
            <el-tooltip :content="$t('本轮盈利 = 当前股东融资后市值 - 当前股东上一轮融资后市值 - 当前股东本轮投资金额')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.roundIncome'">
              <Money v-model="scope.row.roundIncome" unit="w" @paste.native="pasteMe($event, scope.$index, 'roundIncome')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('最新持股比例')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('最新持股比例') }}</span>
            <el-tooltip :content="$t('最新持股比例 = 最新持有股数 / 本轮最新持有股数汇总之和')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.shareRatio'" :rules="detailListRules.shareRatio">
              <Ratio v-model="scope.row.shareRatio" unit="rate" @paste.native="pasteMe($event, scope.$index, 'shareRatio')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('备注') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.remark'">
              <el-input v-model="scope.row.remark" max-length="200" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" fixed="right" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['deal:equityChange:remove']" size="small" type="text" icon="el-icon-delete" @click="delDetail(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-dropdown v-hasPermi="['deal:equityChange:edit']" size="mini" split-button type="primary" @command="handleCommand" @click="addDetail">
          {{ $t('添加') }}<i class="el-icon-arrow-down el-icon--right" />
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="5">{{ $t('添加5行') }}</el-dropdown-item>
            <el-dropdown-item command="10">{{ $t('添加10行') }}</el-dropdown-item>
            <el-dropdown-item command="15">{{ $t('添加15行') }}</el-dropdown-item>
            <el-dropdown-item command="20">{{ $t('添加20行') }}</el-dropdown-item>
            <el-dropdown-item command="30">{{ $t('添加30行') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-tooltip v-model="isAll" :content="$t('请关闭批量修改后再进行计算或保存')" :enterable="false" :manual="true">
          <el-button v-hasPermi="['deal:equityChange:edit']" type="primary" :disabled="isAll" icon="el-icon-c-scale-to-original" size="mini" @click="jisuan">{{ $t("计算") }}</el-button>
        </el-tooltip>
        <el-checkbox v-model="isAll" v-hasPermi="['deal:equityChange:edit']" style="margin-left: 10px;">{{ $t('批量修改-开启后可复制Excel数据') }}</el-checkbox>
      </div>
      <FileTable :list.sync="form.fileList" has-permi="deal:equityChange" data-type="deal_equity_change" :business-id="form.dealId" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="deal:equityChange" :disabled="isAll" :bus-data="form" cache-key="deal_equity_change_cap_table" />
    </div>
  </div>
</template>

<script>
    import Sortable from 'sortablejs'
    import { saveDealEquityChange, getData, listDealEquityChange, getThisFirstAndLastData } from '@/api/deal/equitychange/dealEquityChange'
    import { delDealEquityChangeDetail } from '@/api/deal/equitychange/dealEquityChangeDetail'
    import { listDealContractTerms } from '@/api/deal/terms/dealTerms'
    import { getWebRate, listDealInvestment } from '@/api/deal/investment/dealInvestment'
    import { moneyFormat } from '@/utils/ruoyi'
    import { getDealBase } from '@/api/base/deal/dealBase'
    import MainBodySelect from '@/components/MainBodySelect'
    export default {
      components: {
        MainBodySelect
      },
      data() {
        const checkMinValue = (rule, value, callback) => {
          if (value === undefined || value === null || value === '') {
            callback(new Error(this.$t('必填信息')))
          } else {
            var num = parseFloat(value)
            if (num <= 0) {
              callback(new Error(this.$t('不能为0')))
            } else {
              callback()
            }
          }
        }
        return {
          firstPicker: undefined,
          lastPicker: undefined,
          currentPicker: undefined,
          isAll: false,
          // 表单参数
          form: {
            dealId: undefined,
            exchangeRateWeb: [],
            detailList: [],
            // 股东变更详情-合计-最新持有股数
            totalHoldShare: 0
          },
          afterSharePriceNum: undefined,
          afterSharePriceHide: false,
          // 遮罩层
          loading: false,
          // 是否隐藏其它按钮
          otherBtnHide: false,
          // 表单校验
          rules: {
            companyType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            changeDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            rounds: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            currency: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            roundsType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            amountFinancing: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            enterpriseStage: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            afterSharePrice: [{ required: true, validator: checkMinValue, trigger: ['blur', 'change'] }],
            afterShareNum: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
            afterValuation: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
            dealId: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
          },
          // 查询参数
          queryParams: {
            dealId: this.$route.query.id,
            id: '',
            pageNo: 1
          },
          // 关键条款数据
          termsOptions: [],
          // 股东变更详情加载框
          detailLoading: false,
          // 股东详情信息
          // detailList: [],
          // 股东详情表单验证
          detailListRules: {
            shareholderName: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
            changeType: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
            investAmount: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
            holdShare: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
            shareRatio: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
          },
          // 投资主体数据集合
          restaurants: [],
          // 已有股数是否可编辑
          editExistShareStatus: true,
          changeTypeOptions: [],
          currencyOptions: [],
          dealBaseData: undefined,
          // 是否展示项目名称
          isDealName: this.$attrs.parameter && this.$attrs.parameter.quick && this.$attrs.parameter.quick === 'true'
        }
      },
      computed: {
        pickerOptions() {
          var _this = this
          return {
            disabledDate(time) {
              if (time) {
                var lastPicker = new Date(_this.lastPicker)
                var firstPicker = new Date(_this.firstPicker)
                if (_this.firstPicker !== undefined && _this.lastPicker === undefined) {
                  return new Date(time).getTime() > new Date(firstPicker.setDate(firstPicker.getDate() - 1)).getTime()
                } else if (_this.firstPicker === undefined && _this.lastPicker !== undefined) {
                  return new Date(time).getTime() < new Date(lastPicker.setDate(lastPicker.getDate() + 1)).getTime()
                } else if (_this.firstPicker !== undefined && _this.lastPicker !== undefined) {
                  return new Date(time).getTime() > new Date(firstPicker.setDate(firstPicker.getDate() - 1)).getTime() || new Date(time).getTime() < new Date(lastPicker.setDate(lastPicker.getDate() + 1)).getTime()
                }
              }
              return false
            }
          }
        }
      },
      watch: {
        'form.afterSharePrice': {
          handler(val) {
            this.afterSharePriceNum = this.formatNum(val).toFixed(6)
          }
        }
      },
      mounted() {
        // 加载投资主体数据
        this.loadInvestmentData()
      },
      created() {
        this.getDicts('currency').then(response => {
          this.currencyOptions = response.data
        })
        this.getDicts('equity_change_type').then(response => {
          this.changeTypeOptions = response.data
        })
        this.getDealBase()
      },
      methods: {
        pasteMe(e, index, key) {
          var changeType = this.form.detailList[index].changeType
          this.$forceUpdate()
          e.srcElement.blur()
          if (this.isAll) {
            this.form.detailList[index][key] = ''
            var fields = ['shareholderName', 'investAmount', 'existShare', 'resultShare', 'holdShare', 'shareMarket', 'roundIncome', 'shareRatio']
            const source = e.clipboardData.getData('Text')
            const rows = source.split('\n') // 拆成很多行
            var arr = []
            for (let i = 0; i < rows.length; i++) {
              if (rows[i] !== '') {
                var columns = ''
                // 由于股东名称是文字比较特殊. 而且在第一的位置. 所以给股东位置加了个ID.  如果e.srcElement.id === 'shareholderName', 则说明是第一列. 否则就是其他列.
                if (e.srcElement.id === 'shareholderName') {
                  columns = rows[i].split('\t')
                  columns.forEach((str, strInd) => {
                    if (strInd !== 0) {
                      columns[strInd].replace(/[\r\,\￥]/g, '')
                    }
                  })
                } else {
                  columns = (rows[i].replace(/[\r\,\￥]/g, '')).split('\t')
                }
                arr.push(columns)
              }
            }
            var ind = fields.findIndex(item => item === key)
            var nFields = []
            if (ind || ind === 0) {
              nFields = fields.splice(ind, fields.length)
            }
            if (arr.length === 1) { // 一行
              arr[0].forEach((v, i) => {
                nFields.forEach((n, j) => {
                  if (v && i === j) {
                    // 如果复制的的是股东, 需要给投资主体给他附上ID
                    if (n === 'shareholderName') {
                      this.handleSelectCopy(v, index)
                    } else {
                      if (changeType === 'WBD' && (n === 'investAmount' || n === 'resultShare')) {
                        this.form.detailList[index][n] = e.target.value
                      } else {
                        this.form.detailList[index][n] = this.filterData(v)
                      }
                    }
                  }
                })
              })
            } else if (arr.length > 1) { // 多行
              var barr = []
              arr.forEach((ele, rowIndex) => {
                var obj = {}
                ele.forEach((el, ind) => {
                  nFields.forEach((f, fi) => {
                    if (ind === fi) {
                      if (f === 'shareholderName') {
                        obj[f] = el
                        this.handleSelectCopy(el, index + rowIndex)
                      } else {
                        obj[f] = this.filterData(el)
                      }
                    }
                  })
                })
                barr.push(obj)
              })
              barr.forEach((ele, inde) => {
                for (var keys in ele) {
                  if (keys !== 'shareholderName') {
                    if (changeType === 'WBD' && (keys === 'investAmount' || keys === 'resultShare')) {
                        this.form.detailList[index + inde][keys] = e.target.value
                      } else {
                        this.form.detailList[index + inde][keys] = this.filterData(ele[keys])
                      }
                  }
                }
              })
              console.log('粘贴结束')
            }
          } else {
            const val = e.clipboardData.getData('Text')
            if (key === 'shareholderName') {
             this.form.detailList[index][key] = val
            } else {
              this.form.detailList[index][key] = this.filterData(val)
            }
          }
          this.$forceUpdate()
        },
        filterData(val) {
          var num = ''
          if (val) {
            // 判断是否为金额
            if (typeof val === 'number') {
              num = val
            } else if (val.substr(0, 1) === '-') {
              num = +(val.replace(/[^\d.]/g, '')) * -1
            } else {
              num = +(val.replace(/[^\d.]/g, ''))
            }
            if (num > 999000000000000) {
              num = ''
            }
          }
          return this.formatNum(num)
        },
        // 初始化数据
        init(data) {
          this.loading = true
          this.reset()
          if (data && data.id !== undefined) {
            this.queryParams.id = data.id
          }
          if (this.queryParams.dealId) {
            this.initDealData(data)
          }
        },
        // 根据项目id初始化数据
        initDealData(data) {
          getData(this.queryParams).then(response => {
            this.form = response.data
            this.form.automaticPriceCalculation = (this.form.automaticPriceCalculation === 'true')
            this.form.exchangeRateWeb = JSON.parse((this.form.exchangeRate === undefined || this.form.exchangeRate === null || this.form.exchangeRate === '') ? '[]' : this.form.exchangeRate)
            // 获取当前项目信息币种及其信息
            var _this = this
            getDealBase(this.$route.query.id ? this.$route.query.id : this.form.dealId).then(response => {
              _this.dealBaseData = response.data
              if (!_this.isNotEmpty(_this.form.currency)) {
                _this.form.currency = _this.dealBaseData.currency
              }
              if (_this.form.exchangeRateWeb === undefined || _this.form.exchangeRateWeb === null || _this.form.exchangeRateWeb.length <= 0) {
                _this.settingHoldShareCurrency()
              }
            })
            // 获取融资时间可选择时间段
            if (this.queryParams.id !== undefined && this.queryParams.id !== null && this.queryParams.id !== '') {
              getThisFirstAndLastData(this.form.changeDate, this.form.dealId).then(response => {
                if (response.data !== null) {
                  this.lastPicker = response.data.lastPicker === null ? undefined : response.data.lastPicker
                  this.firstPicker = response.data.firstPicker === null ? undefined : response.data.firstPicker
                }
              })
            }
            this.$nextTick(() => {
              // 融资后公司估值 所有股东的融资后持有市值合计值
              if (this.form.afterValuation === undefined || this.form.afterValuation === null || this.form.afterValuation === '' || this.formatNum(this.form.afterValuation) === 0) {
                this.changeShareMarket()
              }
              // 融资后-公司总股数/注册资本:  获取逻辑: 所有股东最新持有股数合计
              if (this.form.afterShareNum === undefined || this.form.afterShareNum === null || this.form.afterShareNum === '' || this.formatNum(this.form.afterShareNum) === 0) {
                this.form.afterShareNum = this.calcTotalHoldShare()
              }
            })
            this.loading = false
          })
          // 获取当前项目的关键条款数据
          listDealContractTerms(this.queryParams).then(response => {
            this.termsOptions = response.rows
          })
          // 判断已有股数是否可编辑
          listDealEquityChange({ dealId: this.$route.query.id ? this.$route.query.id : this.form.dealId }).then(response => {
            if (response.total === 0) {
              this.editExistShareStatus = false
            } else {
              if (data != null && data.id !== undefined) {
                // 修改
                this.editExistShareStatus = !(response.total === 1 && response.rows[0].id === data.id)
              } else {
                // 新增
                this.editExistShareStatus = response.total > 0
              }
            }
          })
        },
        handleCommand(command) {
          command = parseInt(command)
          this.addDetailMany(command)
        },
        addDetailMany(num) {
          for (var i = 0; i < num; i++) {
            this.addDetail()
          }
        },
        // 添加股东信息
        addDetail() {
          const row = {
            id: undefined,
            shareholderId: '',
            shareholderName: '',
            changeType: 'WBD',
            existShare: 0,
            holdShare: '',
            resultShare: '',
            shareMarket: '',
            roundIncome: '',
            investAmount: '',
            shareRatio: '',
            isNew: true
          }
          if (!(this.form.detailList instanceof Array)) {
            this.$set(this.form, 'detailList', [])
          }
          this.$nextTick(() => {
            this.form.detailList.push(row)
          })
        },
        // 删除付款主体
        delDetail(index, row) {
          const id = row.id
          if (id !== undefined && id !== '' && id != null) {
            this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'warning'
            })
            .then(function() {
              return delDealEquityChangeDetail(id)
            }).then(() => {
              this.form.detailList.splice(index, 1)
              this.delSetHoldShareCurrency()
              return this.msgSuccess(this.$t('删除成功'))
            })
            .catch(function() {})
          } else {
            this.form.detailList.splice(index, 1)
            this.delSetHoldShareCurrency()
          }
        },
        // 选择投资主体触发方法
        querySearch(queryString, cb) {
          const restaurants = this.restaurants
          const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
          // 调用 callback 返回建议列表的数据
          cb(results)
        },
        // 创建股东名称数据
        createFilter(queryString) {
          return (restaurant) => {
            return (restaurant.investorName.toLowerCase().includes(queryString.toLowerCase()))
          }
        },
        // 加载投资主体数据
        loadInvestmentData() {
          listDealInvestment(this.queryParams).then(response => {
            this.restaurants = response.rows
          })
        },
        // 变更类型
        changeTypeMethod(val, index) {
          if (val) {
            if (val === 'WBD') {
              this.form.detailList[index].investAmount = 0
              this.form.detailList[index].resultShare = 0
            }
          }
        },
        // 选择投资主体数据
        handleSelect(item, row) {
          // 遍历判断是否存在这个投资主体
          var flag = false
          this.form.detailList.forEach(detail => {
            if (detail.shareholderId === item.id) {
              flag = true
              return
            }
          })
          if (flag) {
            this.msgError(this.$t('不能重复选择投资主体，请重新选择或者输入！'))
            row.shareholderId = ''
          } else {
            row.shareholderId = item.id
            row.shareholderName = item.investorName
            if (!this.editExistShareStatus) {
              row.existShare = this.formatNum(item.numberOfShares)
            }
          }
          this.settingHoldShareCurrency()
        },
        // 选择投资主体数据 字段
        handleSelectCopy(name, index) {
          if (name !== undefined) {
            name = name.trim()
          }
          // 根据名字找到下拉里的数据. 然后判断列表中出资主体ID是有存在了
          var temp = true
          this.restaurants.some(item => {
            if (item.investorName !== null) {
              item.investorName = item.investorName.trim()
            }
            console.log('搜寻股东与主体相同的名称:', item.investorName, name)
            if (item.investorName === name) {
              temp = false
              var flag = true
              this.form.detailList.some(detail => {
                if (detail.shareholderId === item.id) {
                  this.msgError(this.$t('不能重复选择投资主体，请重新选择或者输入！'))
                  this.form.detailList[index].shareholderId = ''
                  this.form.detailList[index].shareholderName = ''
                  flag = false
                  return true
                }
              })

              if (flag) {
                this.form.detailList[index].shareholderId = item.id
                this.form.detailList[index].shareholderName = item.investorName
                if (!this.editExistShareStatus) {
                  this.form.detailList[index].existShare = this.formatNum(item.numberOfShares)
                }
              }
              return true
            }
            if (temp) {
              this.form.detailList[index].shareholderName = name
              this.form.detailList[index].shareholderId = ''
            }
          })
          this.settingHoldShareCurrency()
          this.$forceUpdate()
        },
        // 配置投资主体股东的币种汇率
        settingHoldShareCurrency() {
          var parseRate = []
          if (this.form.exchangeRateWeb !== undefined && this.form.exchangeRateWeb !== '' && this.form.exchangeRateWeb !== null && this.form.exchangeRateWeb.length > 0) {
            parseRate = this.form.exchangeRateWeb
          }
          var tempParseRate = JSON.parse(JSON.stringify(parseRate))
          var temp = []
          this.form.detailList.forEach(detail => {
            if (detail.shareholderId && this.restaurants) {
              var object = this.restaurants.find(obj => obj.id === detail.shareholderId)
              if (object) {
                if (object.currency !== null && object.currency !== this.form.currency) {
                  const c = parseRate.find(obj => obj.currency === object.currency)
                  const t2 = tempParseRate.find(obj => obj.currency === object.currency)
                  if (!t2) {
                    temp.push({
                      'sourceCurrency': object.currency,
                      'targetCurrency': this.form.currency,
                      'rate': c ? c.currency : undefined
                    })
                  }
                }
              }
            }
          })
          this.form.exchangeRateWeb = temp
          // this.delSetHoldShareCurrency()
          // 确保汇率中有当前项目币种 - 如果项目比重不为空, 并且表单币种不为空,  并且两个币种不相等. 那么就添加上该表单币种对当前项目币种之间的汇率
          var currencyList = []
          this.form.exchangeRateWeb.forEach(item => {
            currencyList.push(item.sourceCurrency)
          })
          if (this.dealBaseData !== null && this.isNotEmpty(this.dealBaseData) && this.isNotEmpty(this.form.currency) && this.form.currency !== this.dealBaseData.currency) {
            if (!currencyList.includes(this.dealBaseData.currency)) {
              this.form.exchangeRateWeb.push({
                sourceCurrency: this.dealBaseData.currency,
                targetCurrency: this.form.currency,
                rate: undefined
              })
            }
          }
          // 获取多币种的汇率
          this.getWebRate()
          this.$forceUpdate()
        },
        getWebRate() {
          this.form.exchangeRateWeb.forEach((item, index) => {
            if (item !== undefined && item.targetCurrency !== undefined && item.sourceCurrency !== undefined) {
              getWebRate(item.targetCurrency, item.sourceCurrency, this.form.changeDate).then(response => {
                if (response.data !== '' && response.data !== null) {
                  item.placeholder = response.data
                  this.$set(this.form.exchangeRateWeb[index], 'placeholder', this.$t('近期汇率参考') + ': ' + response.data)
                  this.$forceUpdate()
                }
              })
            }
          })
        },
        inputPlaceholder(index, val) {
          if (val !== undefined && val !== null && val !== '') {
            val = val.replaceAll('近期汇率参考', '').replaceAll(':', '').trim()
            this.$set(this.form.exchangeRateWeb[index], 'rate', parseFloat(val))
            this.$forceUpdate()
          }
        },
        // 删除时 调整汇率
        delSetHoldShareCurrency() {
          var parseRate = []
          if (this.form.exchangeRateWeb !== undefined && this.form.exchangeRateWeb !== '' && this.form.exchangeRateWeb !== null) {
            parseRate = this.form.exchangeRateWeb
          }
          var temp = JSON.parse(JSON.stringify(parseRate))
          var currentCurrency = []
          this.form.detailList.forEach(detail => {
            if (detail.shareholderId) {
              var object = this.restaurants.find(obj => obj.id === detail.shareholderId)
              if (object) {
                currentCurrency.push(object.currency)
              }
            }
          })
          if (currentCurrency.length <= 0) {
            temp = []
          } else {
            temp.forEach(item => {
              if (!currentCurrency.includes(item.sourceCurrency)) {
                temp.splice(temp.indexOf(item), 1)
              }
            })
          }
          this.form.exchangeRateWeb = temp
        },
        isNotEmpty(val) {
          return !(val === undefined || val === null || val === '')
        },
        formatCurrency(val) {
          const currency = this.currencyOptions.find(obj => obj.dictValue === val)
          if (currency) {
            return currency.dictLabel
          }
          return val
        },
        changeBlurRate(val, currency) {
          if (val && !isNaN(val)) {
            const index = this.form.exchangeRateWeb.findIndex(obj => obj.currency === currency)
            this.$nextTick(() => {
              this.form.exchangeRateWeb[index].rate = val
              this.$forceUpdate()
            })
          }
        },
        // 股东名称改变时校验是否是投资主体
        choiceHoldShare(queryString, index) {
          const restaurants = this.restaurants
          const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
          if (results === undefined || results === null || results === '' || results.length <= 0) {
            this.form.detailList[index].shareholderId = ''
          }
          this.settingHoldShareCurrency()
        },
        afterSharePriceFocus() {
          this.afterSharePriceHide = true
        },
        afterSharePriceChange() {
          this.afterSharePriceHide = false
        },
        getRowKeys(row) {
          return row.id === null || row.id === undefined || row.id === '' ? new Date().getTime() : row.id
        },
        handleIconClick(ev) {
          console.log(ev)
        },
        // 合计
        getSummaries() {
          // 表格中设置ref属性，在数据渲染之后或者updated()之后
          this.$nextTick(() => {
            this.$refs.table.doLayout()
          })
          if (this.editExistShareStatus) {
            if (this.isAll) {
              return [
                this.$t('合计'),
                '-',
                '-',
                '-',
                moneyFormat(this.calcTotalInvestAmount(), 'w'),
                moneyFormat(this.calcTotalResultShare(), 'w'),
                moneyFormat(this.calcTotalHoldShare(), 'w'),
                moneyFormat(this.calcTotalShareMarket(), 'w'),
                moneyFormat(this.calcTotalRoundIncome(), 'w'),
                moneyFormat(this.calcTotalShareRatio())
              ]
            } else {
              return [
                this.$t('合计'),
                '-',
                '-',
                '-',
                moneyFormat(this.calcTotalInvestAmount(), 'w'),
                moneyFormat(this.calcTotalExistShare(), 'w'),
                moneyFormat(this.calcTotalResultShare(), 'w'),
                moneyFormat(this.calcTotalHoldShare(), 'w'),
                moneyFormat(this.calcTotalShareMarket(), 'w'),
                moneyFormat(this.calcTotalRoundIncome(), 'w'),
                moneyFormat(this.calcTotalShareRatio())
              ]
            }
          } else {
            if (this.isAll) {
              return [
                this.$t('合计'),
                '-',
                '-',
                moneyFormat(this.calcTotalInvestAmount(), 'w'),
                moneyFormat(this.calcTotalExistShare(), 'w'),
                moneyFormat(this.calcTotalResultShare(), 'w'),
                moneyFormat(this.calcTotalHoldShare(), 'w'),
                moneyFormat(this.calcTotalShareMarket(), 'w'),
                moneyFormat(this.calcTotalRoundIncome(), 'w'),
                moneyFormat(this.calcTotalShareRatio())
              ]
            } else {
              return [
                this.$t('合计'),
                '-',
                '-',
                '-',
                moneyFormat(this.calcTotalInvestAmount(), 'w'),
                moneyFormat(this.calcTotalExistShare(), 'w'),
                moneyFormat(this.calcTotalResultShare(), 'w'),
                moneyFormat(this.calcTotalHoldShare(), 'w'),
                moneyFormat(this.calcTotalShareMarket(), 'w'),
                moneyFormat(this.calcTotalRoundIncome(), 'w'),
                moneyFormat(this.calcTotalShareRatio())
              ]
            }
          }
        },
        // 点击计算
        jisuan() {
          if (!this.isAll) {
            // 计算最新持有股数；
            this.calcHoldShare()
            // 计算投后股价
            this.calcAfterPrice()
            // 融资后持股市值
            this.calcShareMarket()
            // 计算本轮盈利
            this.calcRoundIncome()
            // 融资后持股市值合计更新融资后公司估值
            this.changeShareMarket()
            // 特殊 - 重新计算融资后-公司总股数/注册资本
            this.changeHoldShare()
            // 计算最新持股比例
            this.calcShareRatio()
          }
          // 将所有数据进行一下万亿校验
          this.checkAllMoney()
        },
        // 计算最新持有股数 = 已有股数 + 变更股数
        calcHoldShare() {
          this.form.detailList.forEach(item => {
            const existShare = (item.existShare === null || item.existShare === undefined || item.existShare === '') ? 0 : item.existShare
            const resultShare = (item.resultShare === null || item.resultShare === undefined || item.resultShare === '') ? 0 : item.resultShare
            item.holdShare = this.formatNum(resultShare) + this.formatNum(existShare)
          })
        },
        // 计算最新持股比例 = 最新持股数 / 本轮最新持有股数汇总之和
        calcShareRatio() {
          this.form.detailList.forEach(item => {
            if (item.holdShare >= 0) {
              var tempHoldShare = (item.holdShare === null || item.holdShare === undefined || item.holdShare === '') ? 0 : item.holdShare
              item.shareRatio = this.formatNum(tempHoldShare) / this.calcTotalHoldShare() * 100
            }
          })
        },
        // 计算融资后持股市值 = 融资后每股价格 * 当前股东最新持股数
        calcShareMarket() {
          // 融资后每股价格
          var pricePerShare = (this.form.afterSharePrice === null || this.form.afterSharePrice === undefined || this.form.afterSharePrice === '') ? 0 : this.formatNum(this.form.afterSharePrice)
          // 本轮变更股数绝对值汇总
          const resultShareAbs = this.calcResultShareABS()
          if (pricePerShare === 0) {
            this.form.detailList.forEach(item => {
              item.shareMarket = 0
            })
            return
          }
          if (resultShareAbs !== '' && resultShareAbs !== 0) {
            this.form.detailList.forEach(item => {
              if (resultShareAbs > 0) {
                item.shareMarket = pricePerShare * this.formatNum(item.holdShare)
              }
            })
          }
        },
        // 计算本轮盈利 = 当前股东融资后市值 - 当前股东上一轮融资后市值 - 当前股东本轮投资金额
        calcRoundIncome() {
          this.form.detailList.forEach(item => {
            const shareMarket = (item.shareMarket === null || item.shareMarket === undefined || item.shareMarket === '') ? 0 : item.shareMarket
            const investAmount = item.investAmount === null || item.investAmount === undefined || item.investAmount === '' ? 0 : item.investAmount
            const prevShareMarket = item.prevShareMarket === null || item.prevShareMarket === undefined || item.prevShareMarket === '' ? 0 : item.prevShareMarket
            // 获取上一轮融资后市值
            if (item.shareholderName !== '') {
              // 本轮盈利 = 当前股东融资后市值 - 当前股东上一轮融资后市值 - 当前股东本轮投资金额
              item.roundIncome = this.formatNum(shareMarket) - this.formatNum(prevShareMarket) - this.formatNum(investAmount)
            }
        })
      },
        // 融资后每股价格 = 本轮投资金额绝对值汇总 / 本轮变更股数绝对值汇总
        calcAfterPrice() {
          // 1、获取本轮投资金额绝对值
          var totalInvestAmount = this.calcInvestAmountABS()
          // 2、获取本轮变更股数绝对值(本轮投资金额为0的不算数)
          var totalResultShare = this.calcResultShareNotInvestAmountZero()

          if (isNaN(totalInvestAmount)) {
            totalInvestAmount = 0
          }
          if (isNaN(totalResultShare)) {
            totalResultShare = 1
          }

          if (totalResultShare !== '' && totalInvestAmount !== '' && totalResultShare !== 0) {
            if (this.form.automaticPriceCalculation) {
              this.form.afterSharePrice = totalInvestAmount / totalResultShare
            }
          }
        },
        // (本轮投资金额变化后. 计算童子后每股价格.) * 最新持有股数 = 融资后持股市值
        calcResultShareNotInvestAmountZero() {
          let totalResultShare = 0
          this.form.detailList.forEach(item => {
            if (item.investAmount !== 0) {
              let resultShare = (item.resultShare === null || item.resultShare === undefined || item.resultShare === '') ? 0 : item.resultShare
              if (resultShare < 0) {
                resultShare = Math.abs(this.formatNum(resultShare))
              }
              totalResultShare += this.formatNum(resultShare)
            }
          })
          return totalResultShare
        },
        // 获取本轮投资金额绝对值汇总
        calcInvestAmountABS() {
          let totalInvestAmount = 0
          this.form.detailList.forEach(item => {
            if (item.investAmount === '' || item.investAmount === undefined || item.investAmount === null) {
              item.investAmount = 0
            }
            let investAmount = this.formatNum(item.investAmount)
            if (investAmount < 0) {
              investAmount = Math.abs(investAmount)
            }
            totalInvestAmount += investAmount
          })
          return totalInvestAmount
        },
        // 获取本轮变更股数绝对值汇总
        calcResultShareABS() {
          let totalResultShare = 0
          this.form.detailList.forEach(item => {
            let holdShare = (item.holdShare === null || item.holdShare === undefined || item.holdShare === '') ? 0 : this.formatNum(item.holdShare)
              if (holdShare < 0) {
                holdShare = Math.abs(holdShare)
              }
              totalResultShare += holdShare
          })
          return totalResultShare
        },
        // 投后股价变化，计算融资后持股市值
        /* calcMarketByPrice() {
          if (this.form.afterSharePrice != null) {
            this.form.detailList.forEach(item => {
              const holdShare = item.holdShare || 0
              item.shareMarket = this.formatNum(holdShare) * this.formatNum(this.form.afterSharePrice)
            })
          }
          this.appenHZ()
        },*/
        // 合计==>最新持有股数
        calcTotalHoldShare() {
          let totalShare = 0
          this.form.detailList.forEach(item => {
            if (item.holdShare !== '') {
              totalShare += this.formatNum(item.holdShare)
            }
          })
          return totalShare
        },
        // 合计==>获取本轮投资金额总额
        calcTotalInvestAmount() {
          let totalInvestAmount = 0
          this.form.detailList.forEach(item => {
            if (item.investAmount !== '') {
              totalInvestAmount += this.formatNum(item.investAmount)
            }
          })
          return totalInvestAmount
        },
        // 合计==>已有股数
        calcTotalExistShare() {
          let totalExistShare = 0
          this.form.detailList.forEach(item => {
            if (item.existShare !== '') {
              totalExistShare += this.formatNum(item.existShare)
            }
          })
          return totalExistShare
        },
        // 合计==>变更股数
        calcTotalResultShare() {
          let totalResultShare = 0
          this.form.detailList.forEach(item => {
            if (item.resultShare !== '') {
              totalResultShare += this.formatNum(item.resultShare)
            }
          })
          return totalResultShare
        },
        // 合计==>融资后持股市值
        calcTotalShareMarket() {
          let totalShareMarket = 0
          this.form.detailList.forEach(item => {
            if (item.shareMarket !== '') {
              totalShareMarket += this.formatNum(item.shareMarket)
            }
          })
          return totalShareMarket
        },
        // 合计==>本轮盈利
        calcTotalRoundIncome() {
          let totalRoundIncome = 0
          this.form.detailList.forEach(item => {
            if (item.roundIncome !== '') {
              totalRoundIncome += this.formatNum(item.roundIncome)
            }
          })
          return totalRoundIncome
        },
        // 合计==>最新持股比例
        calcTotalShareRatio() {
          let totalShareRatio = 0
          this.form.detailList.forEach(item => {
            if (item.shareRatio !== '') {
              totalShareRatio += this.formatNum(item.shareRatio)
            }
          })
          return totalShareRatio
        },
        // 融资后持股市值变化后 更新 融资后公司估值
        changeShareMarket() {
          const detailList = this.form.detailList
          var tempSum = 0
          if (detailList !== undefined && detailList !== null && detailList.length > 0) {
            detailList.forEach(item => {
              var temp = this.formatNum(item.shareMarket)
              if (!isNaN(temp)) {
                tempSum += temp
              }
            })
            this.form.afterValuation = tempSum
          }
        },
        // 融资后-公司总股数/注册资本 变化后  自动计算  自动计算/可修改	所有股东最新持有股数合计
        changeHoldShare() {
          const detailList = this.form.detailList
          if (detailList !== undefined && detailList !== null && detailList.length > 0) {
            var tempSum = 0
            detailList.forEach(item => {
              var temp = this.formatNum(item.holdShare)
              tempSum += temp
            })
            this.form.afterShareNum = tempSum
          }
          // 最后根据 最新持有股数 计算最新持股比例
        },
        // 表单重置
        reset() {
          this.lastPicker = undefined
          this.firstPicker = undefined
          this.form = {
            id: undefined,
            exchangeRateWeb: [],
            dealId: this.$route.query.id,
            changeDate: undefined,
            afterShareNum: undefined,
            currency: undefined,
            amountFinancing: undefined,
            afterValuation: undefined,
            roundsType: undefined,
            rounds: undefined,
            automaticPriceCalculation: true,
            enterpriseStage: undefined,
            beforeValuation: undefined,
            beforeShareNum: undefined,
            afterSharePrice: undefined,
            termsId: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined,
            remark: undefined,
            companyType: undefined,
            syncToValuation: 'N',
            detailList: []
          }
          this.queryParams.id = ''
          this.resetForm('form')
        },
        // 取消按钮
        cancel() {
          if (this.$parent.$parent.formOpen !== undefined) {
            this.$parent.$parent.formOpen = false
          }
          if (this.$parent.$parent.capTableOpen !== undefined) {
            this.$parent.$parent.capTableOpen = false
          }
          this.$parent.$parent.reset()
        },
        // 关闭form页面
        closeForm() {
          // 关闭form页面遮罩层
          this.loading = false
          // 关闭form页面
          if (this.$parent.$parent.formOpen !== undefined) {
            this.$parent.$parent.formOpen = false
          }
          if (this.$parent.$parent.capTableOpen !== undefined) {
            this.$parent.$parent.capTableOpen = false
          }
          // 刷新list页面
          if (this.$parent.$parent.getList !== undefined) {
            this.$parent.$parent.getList()
          }
        },
        /** 提交按钮 */
        submitForm: function() {
          this.$refs['form'].validate(valid => {
            if (valid) {
              var _this = this
              if (this.form.syncToValuation === 'N') {
                this.$confirm(this.$t('是否同步沉淀数据到项目估值?'), this.$t('提示'), {
                  confirmButtonText: this.$t('同步'),
                  cancelButtonText: this.$t('不同步'),
                  type: 'warning'
                }).then(() => {
                  _this.form.syncToValuation = 'Y'
                  _this.submitFormSave()
                }).catch(() => {
                  _this.form.syncToValuation = 'N'
                  _this.submitFormSave()
                })
              } else {
                this.form.syncToValuation = 'Y'
                this.submitFormSave()
              }
            } else {
              this.locationError(document)
            }
          })
        },
        submitFormSave() {
          this.loading = true
          this.form.exchangeRate = JSON.stringify(this.form.exchangeRateWeb)
          this.form.companyId = this.$route.query.companyId
          saveDealEquityChange(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        },
        rowDrop() {
          // 行拖拽
          const _this = this
          const tbody2 = this.$refs.table.$el.querySelector('.el-table__body-wrapper tbody')
          Sortable.create(tbody2, {
            handle: '.handle',
            animation: 500,
            fallbackOnBody: true,
            onChoose() {
              // 选择元素
              _this.form.detailList[_this.form.detailList.length - 1].fixed = false
            },
            onUnchoose: function(evt) {
              // 取消选择元素
              if (evt) {
                _this.form.detailList[_this.form.detailList.length - 1].fixed = 'right'
              }
            },
            onEnd(evt) {
              _this.form.detailList.splice(evt.newIndex, 0, _this.form.detailList.splice(evt.oldIndex, 1)[0])
              var newArray = _this.form.detailList.slice(0)
              _this.form.detailList = []
              _this.$nextTick(() => {
                _this.form.detailList = newArray
                _this.form.detailList.forEach((item, index) => {
                  item.rowSort = index + 1
                })
              })
            }
          })
          this.$forceUpdate()
        },
        // 校验页面中所有的金额是否超过指定值
        checkAllMoney() {
          // 融资总金额
          this.form.amountFinancing = this.formatNum(this.form.amountFinancing)
          // 融资前公司估值
          this.form.beforeValuation = this.formatNum(this.form.beforeValuation)
          // 融资后公司估值
          this.form.afterValuation = this.formatNum(this.form.afterValuation)
          // 融资前-公司总股数/注册资本
          this.form.beforeShareNum = this.formatNum(this.form.beforeShareNum)
          // 融资后-公司总股数/注册资本
          this.form.afterShareNum = this.formatNum(this.form.afterShareNum)
          // 融资后每股价格
          if (this.form.automaticPriceCalculation) {
            this.form.afterSharePrice = this.formatNum(this.form.afterSharePrice)
          }
          this.form.detailList && this.form.detailList.forEach(item => {
            // 本轮投资金额
            item.investAmount = this.formatNum(item.investAmount)
            // 已有股数
            item.existShare = this.formatNum(item.existShare)
            // 变更股数
            item.resultShare = this.formatNum(item.resultShare)
            // 最新持有股数
            item.holdShare = this.formatNum(item.holdShare)
            // 融资后持股市值
            item.shareMarket = this.formatNum(item.shareMarket)
            // 本轮盈利
            item.roundIncome = this.formatNum(item.roundIncome)
            // 最新持股比例
            item.shareRatio = this.formatNum(item.shareRatio)
          })
          this.$forceUpdate()
        },
        formatNum(val) {
          if (val !== undefined && val !== null && val !== '' && !isNaN(val)) {
            if (Number(val)) {
              var result = parseFloat(val)
              if (result > 999000000000000) {
                this.msgError(this.$t('警告，金额不能大于等于千万亿！'))
                return 0
              }
              return result
            } else {
              return 0
            }
          } else {
            return 0
          }
        },
        changeDeal(dealId) {
          console.log(dealId)
          if (dealId) {
            this.queryParams.dealId = dealId
            this.initDealData(this.form)
          }
        }
      }
    }
</script>
<style lang="scss" scoped>
  .handle, .canDrag {
    cursor: move;
    user-select:none;
  }

  ::v-deep .hover-row > td {
    background-color: #fff !important;
  }

  ::v-deep .sortable-chosen > td {
    // 拖动的样式
    background-color: #eff2f6 !important;
  }

  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
    // 修复拖拽的时候hover的不消失的问题
    background-color: #fff;
  }
</style>
